package com.itheima.service.impl;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.dto.MemberLoginDto;
import com.itheima.mapper.MemberMapper;
import com.itheima.pojo.entity.Member;
import com.itheima.service.MemberService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Objects;
import java.util.Optional;

/**
 * @className MemberServiceImpl
 */
@Service
@RequiredArgsConstructor
public class MemberServiceImpl implements MemberService {

    private final RedisTemplate<String, Integer> redisTemplate;
    private final MemberMapper memberMapper;

    /**
     * 会员登录
     * @param memberLoginDto 登录条件：手机号、验证码
     * @return String
     **/
    public String memberLogin(MemberLoginDto memberLoginDto) {
        // 从Redis中获取登录验证码并进行验证
        return Optional.ofNullable(redisTemplate.opsForValue().get("Login:" + memberLoginDto.getTelephone()))
                // 验证码匹配检查
                .filter(code -> memberLoginDto.getValidateCode().equals(String.valueOf(code)))
                .map(validCode -> {
                    // 检查成员是否存在，不存在则创建新成员
                    Optional.ofNullable(memberMapper.selectMemberByQuery(memberLoginDto.getTelephone(), null))
                            .orElseGet(() -> {
                                // 创建新成员并插入数据库
                                Member member = new Member();
                                member.setPhoneNumber(memberLoginDto.getTelephone());
                                member.setRegTime(LocalDate.now());
                                memberMapper.insertMember(member);
                                return member;
                            });
                    // 登录成功消息
                    return MessageConstant.LOGIN_SUCCESS;
                }).orElse(MessageConstant.VALIDATECODE_ERROR);
    }
}
